from flask import Blueprint, request
from flask_jwt_extended import get_jwt_identity, jwt_required
from flask_mail import Message
from exts import mail
from service.user_service import register, change_password, login, get_user_list, get_user_info, update_info, \
    update_avatar
from utils import response, get_auth_code
from log import logger

user_bp = Blueprint("user", __name__, url_prefix="/user")


@user_bp.route("/login", methods=['POST'])
def login_router():
    body = request.get_json()

    try:
        username = body["username"]
        password = body["password"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    try:
        data = login(username=username,
                     password=password)
        logger.info(f"用户{username}已登录")
        return response(200, "登录成功", data)
    except Exception as ex:
        return response(500, str(ex), None)


@user_bp.route("/getUserList", methods=['GET'])
def get_user_list_router():
    try:
        user_list = get_user_list()

        return response(200, "获取用户列表成功", user_list)
    except Exception as ex:
        return response(500, str(ex), None)


@user_bp.route("/getUserInfo", methods=['GET'])
@jwt_required()
def get_user_info_router():
    try:
        sub = get_jwt_identity()
        user_info = get_user_info(sub['username'])

        return response(200, "获取用户信息成功", user_info)
    except Exception as ex:
        return response(500, str(ex), None)


@user_bp.route("/register", methods=['POST'])
def register_router():
    body = request.get_json()
    try:
        username = body["username"]
        password = body["password"]
        email = body["email"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    nickname = body.get("nickname")

    try:
        register(username=username,
                 password=password,
                 email=email,
                 nickname=nickname)

        return response(200, "注册成功", None)
    except Exception as ex:
        return response(500, str(ex), None)


@user_bp.route("/changePassword", methods=['PUT'])
@jwt_required()
def change_password_router():
    body = request.get_json()
    try:
        old_password = body["old_password"]
        new_password = body["new_password"]
        ver_password = body["ver_password"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    sub = get_jwt_identity()
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return response(401,"Token 头部格式异常", None)

    token = auth_header.split(" ")[1]

    try:
        change_password(user_id=sub['user_id'],
                        old_password=old_password,
                        new_password=new_password,
                        ver_password=ver_password,
                        token=token)

        return response(200, "密码修改成功", None)
    except Exception as ex:
        return response(500, str(ex), None)


@user_bp.route("/updateInfo", methods=['PUT'])
@jwt_required()
def update_info_router():
    body = request.get_json()

    nickname = body.get("nickname")
    email = body.get("email")

    sub = get_jwt_identity()

    try:
        update_info(user_id=sub['user_id'],
                    email=email,
                    nickname=nickname)

        return response(200, "个人信息更新成功", None)
    except Exception as ex:
        return response(500, str(ex), None)


@user_bp.route("/mail", methods=['GET'])
def mail_router():
    code = get_auth_code()

    message = Message(subject="验证码",
                      recipients=["986961742@qq.com"],
                      body=f"刘肥子邀请您加入网站，验证码:{code}")
    message.charset = 'utf-8'
    mail.send(message)
    return response(200, "验证码发送成功", None)


@user_bp.route("/updateAvatar", methods=['PUT'])
@jwt_required()
def update_avatar_router():
    try:
        file = request.files
        avatar = file["avatar"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    sub = get_jwt_identity()

    try:
        update_avatar(user_id=sub['user_id'],
                      avatar=avatar)

        return response(200, "头像上传成功", None)
    except Exception as ex:
        return response(500, str(ex), None)
